﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;

namespace Camelot.SharePointIntegration.IntegrationService
{
    internal class XmlValidator
    {
        public bool IsValid { get; private set; }
        public string ErrorMessage { get; private set; }

        public XmlDocument LoadXml(string xmlFile, string xmlSchema)
        {
            IsValid = true;
            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlFile);

                using (var sr = new StringReader(xmlSchema))
                {
                    using (var schemaReader = XmlReader.Create(sr))
                    {
                        xmlDoc.Schemas.Add(null, schemaReader);
                        xmlDoc.Validate(new ValidationEventHandler(ValidationEventHandler));
                        return xmlDoc;
                    }
                }
            }
            catch (Exception ex)
            {
                IsValid = false;
                ErrorMessage = ex.Message;
                return null;
            }
        }

        private void ValidationEventHandler(object sender, ValidationEventArgs e)
        {
            IsValid = false;
            ErrorMessage = e.Message;
        }
    }
}
